<template>
  <div>
    <NavigationBar></NavigationBar>
    <main>
      <!-- 📌 隐私声明 -->
      <section class="page-section" style="margin-bottom: 20px;">
        <el-alert
          :title="$t('privacyTitle')"
          :description="$t('privacyText')"
          type="info"
          show-icon
          closable
        >
        </el-alert>
      </section>

      <section class="page-section">
        <el-header>
          <h2>📊 {{ $t('vl1') }}</h2>
        </el-header>

        <el-row :gutter="20" class="stat-row">
          <el-col :span="4" v-for="item in stats" :key="item.label">
            <el-card shadow="hover">
              <div>
                <div style="font-size: 16px; color: #666">{{ item.label }}</div>
                <div style="font-size: 28px; font-weight: bold">{{ item.value }}</div>
                <div v-if="item.change !== undefined" style="color: item.change >= 0 ? 'green' : 'red'">
                  {{ item.changeText }}
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <el-divider content-position="left">🌍 {{ $t('vl2') }}</el-divider>

        <div id="map" style="width: 80%; height: 500px; border-radius: 8px; border: 1px solid #ccc; margin: 0 auto;">
        </div>

        <el-divider content-position="left">🧑‍💻 {{ $t('vl3') }}</el-divider>

        <el-table :data="visitors" stripe style="width: 100%">
          <el-table-column prop="country" :label="$t('vl4')"></el-table-column>
          <el-table-column prop="region" :label="$t('vl5')"></el-table-column>
          <el-table-column prop="browser" :label="$t('vl6')"></el-table-column>
          <el-table-column prop="os" :label="$t('vl7')"></el-table-column>
          <el-table-column prop="time" :label="$t('vl8')"></el-table-column>
        </el-table>

        <BackToTop></BackToTop>
      </section>
    </main>
  </div>
</template>



<script setup>
import BackToTop from './general/BackToTop.vue'
import NavigationBar from './general/NavigationBar.vue'
import config from '@/config'
import { useI18n } from 'vue-i18n'
import { ref, onMounted, onUnmounted, watch } from 'vue'
import 'leaflet/dist/leaflet.css'
import L from 'leaflet'

const { t, locale } = useI18n()

const stats = ref([])
const visitors = ref([])
const map = ref(null)
let visitData = null   // 缓存原始数据

// 更新 stats 的函数
function updateStats(data) {
  stats.value = [
    {
      label: t('vl9'),
      value: data.stats.today,
      change: data.stats.today - data.stats.yesterday,
      changeText: `${data.stats.today - data.stats.yesterday} (${(
        (data.stats.today - data.stats.yesterday) /
        Math.max(1, data.stats.yesterday) *
        100
      ).toFixed(2)}%)`,
    },
    { label: t('vl10'), value: data.stats.yesterday },
    { label: t('vl11'), value: data.stats.last7 },
    { label: t('vl12'), value: data.stats.prev7 },
    { label: t('vl13'), value: data.stats.last30 },
    { label: t('vl14'), value: data.stats.total },
  ]
}

// 拉取数据
const fetchData = async () => {
  const res = await fetch(config.apiUrl + 'visit_dashboard.php')
  const data = await res.json()
  visitData = data   // 保存一份原始数据，方便切换语言时用

  updateStats(data)
  visitors.value = data.visitors

  data.mapPoints.forEach(p => {
    L.circleMarker([p.lat, p.lon], { radius: 3, color: 'red' })
      .bindPopup(p.label)
      .addTo(map.value)
  })
}

// ✅ 监听语言切换
watch(locale, () => {
  if (visitData) {
    updateStats(visitData)
  }
})

onMounted(async () => {
  map.value = L.map('map', { scrollWheelZoom: false }).setView([20, 0], 2)

  L.tileLayer('https://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}{r}.png', {
    attribution:
      '&copy; <a href="https://carto.com/">CARTO</a>, &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
  }).addTo(map.value)

  const disclaimer = L.control({ position: 'bottomright' })
  disclaimer.onAdd = function () {
    const div = L.DomUtil.create('div', 'map-disclaimer')
    div.innerHTML = 'Disclaimer: Location data is approximate and for visualization only.'
    div.style.background = 'rgba(255, 255, 255, 0.8)'
    div.style.padding = '6px'
    div.style.fontSize = '12px'
    div.style.borderRadius = '4px'
    return div
  }
  disclaimer.addTo(map.value)

  await fetchData()
})

onUnmounted(() => {
  if (map.value) {
    map.value.remove()
    map.value = null
  }
})
</script>


<style scoped>
.stat-row {
  margin-bottom: 24px;
}
</style>
